import pandas as pd
import json
import os


# 将请求字段拼接完整
def getStr(dataFrame, row):
    query = dataFrame.iloc[row, 0]
    for col in range(1, 5):
        query += "."
        query += str(dataFrame.iloc[row, col])

    return query


# 获取每一个sheet的数据集合
def getAggregate(dataFrame, judgeRow):
    FieldDict, InputsList, ThresholdDict = {}, [], {}
    rowNum = dataFrame.shape[0]
    for row in range(1, rowNum):
        index = getStr(dataFrame, row)

        if dataFrame.iloc[row, judgeRow]:
            InputsList.append(index)
            FieldDict[index] = dataFrame.iloc[row, 6]
            ThresholdDict[dataFrame.iloc[row, 6]] = dataFrame.iloc[row, 8]

    return FieldDict, InputsList, ThresholdDict


# 获取请求数据和字段对应，给实时通信用
def getData(filePath):
    InputsData, FieldData, ThresholdData = {}, {}, {}

    sheetNames = list(pd.read_excel(filePath, sheet_name=None).keys())

    for sheet in range(0, len(sheetNames)):
        dataFrame = pd.read_excel(filePath, sheet_name=sheet, header=None)

        FieldDict, InputsList, ThresholdDict = getAggregate(dataFrame, 9)

        FieldData[sheetNames[sheet]] = FieldDict

        InputsData[sheetNames[sheet]] = {"inputs": InputsList}

        ThresholdData[sheetNames[sheet]] = ThresholdDict

    return InputsData, FieldData, ThresholdData


if __name__ == "__main__":
    print("wait...")

    inFile = os.path.dirname(os.path.realpath(__file__)) + "\\supos_data.xlsx"

    request_inputs = (
        os.path.dirname(os.path.realpath(__file__)) + "\\request_inputs.json"
    )
    replace_field = os.path.dirname(os.path.realpath(__file__)) + "\\replace_field.json"
    judge_threshold = (
        os.path.dirname(os.path.realpath(__file__)) + "\\judge_threshold.json"
    )

    InputsData, FieldData, ThresholdData = getData(inFile)

    with open(request_inputs, "w", encoding="utf8") as f:
        json.dump(InputsData, f)

    with open(replace_field, "w", encoding="utf8") as f:
        json.dump(FieldData, f)

    with open(judge_threshold, "w", encoding="utf8") as f:
        json.dump(ThresholdData, f)

    print("completed")
    # os.system("pause")
